import React, { useState, useEffect, Dispatch } from 'react';
import {
  Button,
  Input,
  Dropdown,
  Menu,
  Modal,
  Empty,
  Form,
  Message,
  Skeleton,
} from '@arco-design/web-react';
import { IconMore, IconPlus } from '@arco-design/web-react/icon';
import {
  RoleList,
  RoleDel,
  RoleAdd,
  RoleEdit,
} from '@/api/modules/authentication';
import { Role } from '@/api/interface/authentication';
import debounce from 'lodash/debounce';
import cs from 'classnames';
import styles from '../../style/index.module.less';
import ModalTitle from '@/components/ModalTitle';

type ActionType = 'edit' | 'add';

const { TextArea } = Input;
const { Search } = Input;
const FormItem = Form.Item;

interface Props {
  t: unknown;
  rtl: boolean;
  role: Role;
  setRole: Dispatch<React.SetStateAction<Role>>;
}

function RoleTree({ t, rtl, role, setRole }: Props) {
  const [loading, setLoading] = useState(false);
  const [roleData, serRoleData] = useState<Role[]>([]);
  const [roleList, setRoleList] = useState<Role[]>([]);
  useEffect(() => {
    getRoleList();
  }, []);

  const getRoleList = async (isLoading = true) => {
    try {
      isLoading && setLoading(true);
      const { data } = await RoleList();
      setRoleList(data);
      serRoleData(data);
      data.length && setRole(data[0]);
    } finally {
      setLoading(false);
    }
  };

  const searchChange = debounce((value) => {
    if (!value) return setRoleList(roleData);
    setRoleList(
      roleList.filter(
        (item) => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1
      )
    );
  }, 500);

  const delRole = (item) => {
    Modal.warning({
      title: `${t['auth.delete.title']}`,
      content: (
        <>
          {t['auth.delete.content'] + ' '}
          <span style={{ color: 'rgb(247, 101, 96)' }}>{`"${item.name}"`}</span>
          {rtl ? ' ؟' : ' ?'}
        </>
      ),
      okButtonProps: { status: 'danger' },
      okText: `${t['auth.operations.delete']}`,
      style: { textAlign: 'center' },
      closable: true,
      onOk: async () => {
        await RoleDel({ id: item.id });
        Message.success(t['auth.delete.success']);
        getRoleList(false);
      },
    });
  };

  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [action, setAction] = useState<{
    role?: Role;
    type?: ActionType;
  }>({});

  const actionText =
    action.type == 'add'
      ? t['auth.operations.add.role']
      : t['auth.operations.edit.role'];

  const actionRole = (role: Role, type: ActionType) => {
    setAction({ role, type });
    setVisible(true);
    if (type === 'add') form.resetFields();
    else form.setFieldsValue(role);
  };

  const [actionLoading, setActionLoading] = useState(false);
  const onSubmit = () => {
    form.validate(async (errors, values) => {
      if (errors) return;
      try {
        setActionLoading(true);
        const api = action.type == 'add' ? RoleAdd : RoleEdit;
        await api({ ...action.role, ...values });
        setVisible(false);
        Message.success(t['auth.save.success']);
        getRoleList(false);
      } finally {
        setActionLoading(false);
      }
    });
  };

  const dropList = (item) => {
    return (
      <Menu>
        <Menu.Item key="1" onClick={() => actionRole(item, 'edit')}>
          {t['auth.operations.edit']}
        </Menu.Item>
        <Menu.Item key="2" onClick={() => delRole(item)}>
          {t['auth.operations.delete']}
        </Menu.Item>
      </Menu>
    );
  };

  const InoperableRole = [
    'SUPER_ADMIN',
    'ADMIN',
    'MEMBER',
    'HIDDEN',
    'INVESTIGATOR',
  ];

  return (
    <>
      <Search
        onChange={searchChange}
        placeholder={t['auth.input.placeholder.role']}
        className={styles['role-search']}
      />

      <Skeleton text={{ rows: 11 }} loading={loading}>
        <div className={styles['role-list']}>
          {roleList.length ? (
            roleList.map((item) => {
              return (
                <div
                  key={item.id}
                  className={cs(
                    item.id === role.id
                      ? styles['role-item-active']
                      : styles['role-item']
                  )}
                >
                  <span
                    className={styles['role-text']}
                    onClick={() => setRole(item)}
                  >
                    {item[rtl ? 'nameAr' : 'name'] || item['name']}
                  </span>
                  <Dropdown droplist={dropList(item)} trigger="click">
                    <IconMore
                      className={styles['role-icon']}
                      style={{
                        display: InoperableRole.includes(item.level) && 'none',
                      }}
                    />
                  </Dropdown>
                </div>
              );
            })
          ) : (
            <Empty className={styles['role-empty']} />
          )}
        </div>
      </Skeleton>

      <Button
        type="primary"
        icon={<IconPlus />}
        className={styles['role-add']}
        onClick={() => actionRole({}, 'add')}
      >
        {t['auth.operations.add.role']}
      </Button>

      {/* action modal */}
      <Modal
        title={<ModalTitle title={actionText} />}
        visible={visible}
        onCancel={() => setVisible(false)}
        onOk={() => onSubmit()}
        confirmLoading={actionLoading}
        okText={actionText}
        cancelText={t['auth.operations.cancel']}
      >
        <Form
          autoComplete="off"
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <FormItem
            label={t['auth.role.form.name']}
            field="name"
            rules={[
              { required: true, message: t['auth.input.placeholder.role'] },
            ]}
          >
            <Input
              placeholder={t['auth.input.placeholder.role']}
              maxLength={20}
            />
          </FormItem>
          <FormItem label={t['auth.role.form.description']} field="description">
            <TextArea
              placeholder={t['auth.input.placeholder.description']}
              maxLength={124}
              showWordLimit
              autoSize={{ minRows: 3, maxRows: 10 }}
            />
          </FormItem>
        </Form>
      </Modal>
    </>
  );
}

export default RoleTree;
